package com.txtsqlclient.ws;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import Acme.Serve.ServeSessionManager;

import com.txtsqlclient.domain.DataSourceType;

@SuppressWarnings("serial")
public class ConfigServlet extends BaseServlet {

	public static final String GET_DATA_SOURCE_TYPES_SERVLET_PATH = "/GetDataSourceTypes";
	private static Log LOGGER = LogFactory.getLog(ConfigServlet.class);

	protected void processRequest(HttpServletRequest req,
			HttpServletResponse res) throws IOException {
		LOGGER.info("Request received for Configuration at: "
				+ DateFormat.getDateTimeInstance().format(
						Calendar.getInstance().getTime()));
		String url = req.getServletPath();
		if (url.equals(ConfigServlet.GET_DATA_SOURCE_TYPES_SERVLET_PATH)) {
			handleGetDatabaseTypes(req, res);
		}
	}

	protected void handleGetDatabaseTypes(HttpServletRequest req,
			HttpServletResponse res) throws IOException {
		res.setContentType("text/xml; charset=utf-8");
		ServletOutputStream out = res.getOutputStream();
		StringBuffer buff = new StringBuffer();

		buff.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		buff
				.append("<p:DataSourceTypes xmlns:p='http://code.google.com/p/txt-sql-client' "
						+ ServeSessionManager.SESSION_COOKIE_NAME
						+ "='"
						+ req.getSession().getId() + "'>");
		for (DataSourceType dst : DataSourceType.getAllTypes()) {
			buff.append("<DataSourceType>");
			buff.append("<Identifier>" + dst.getIdentifier() + "</Identifier>");
			buff.append("<Name>" + dst.getName() + "</Name>");
			buff.append("<IsDatabase>" + dst.isDatabase() + "</IsDatabase>");
			buff.append("</DataSourceType>");
		}
		buff.append("</p:DataSourceTypes>");
		res.setContentLength(buff.length());

		// buff.append("hello");
		out.print(buff.toString());
		out.flush();
		out.close();
	}
}
